import React, { Component, ErrorInfo, ReactNode } from 'react';
import { Button, Result } from 'antd';
import { useNavigate } from 'react-router-dom';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
  errorInfo?: ErrorInfo;
}

class ErrorBoundaryClass extends Component<Props, State> {
  public state: State = {
    hasError: false
  };

  public static getDerivedStateFromError(error: Error): State {
    // 更新 state 使下一次渲染可以显示降级 UI
    return {
      hasError: true,
      error: error
    };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // 你同样可以将错误日志上报给服务器
    console.error('ErrorBoundary caught an error', error, errorInfo);
    this.setState({
      error: error,
      errorInfo: errorInfo
    });
  }

  public render() {
    if (this.state.hasError) {
      // 你可以渲染任何自定义的降级 UI
      return this.props.fallback || (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100vh',
          backgroundColor: '#000'
        }}>
          <Result
            status="error"
            title="页面出现错误"
            subTitle="抱歉，页面出现了意外错误，请刷新页面重试"
            extra={[
              <Button 
                type="primary" 
                key="refresh"
                onClick={() => window.location.reload()}
              >
                刷新页面
              </Button>,
              <Button 
                key="home"
                onClick={() => window.location.href = '/'}
              >
                返回首页
              </Button>
            ]}
          >
            {this.state.error && (
              <div style={{ 
                marginTop: 24, 
                padding: 24, 
                backgroundColor: 'rgba(255,255,255,0.1)',
                borderRadius: 8,
                textAlign: 'left'
              }}>
                <h3 style={{ color: '#fff' }}>错误详情:</h3>
                <p style={{ color: '#ff7875' }}>{this.state.error.toString()}</p>
                {this.state.errorInfo && (
                  <details style={{ whiteSpace: 'pre-wrap', color: '#aaa' }}>
                    {this.state.errorInfo.componentStack}
                  </details>
                )}
              </div>
            )}
          </Result>
        </div>
      );
    }

    return this.props.children;
  }
}

// 包装组件以使用 hooks
const ErrorBoundary: React.FC<Props> = (props) => {
  return <ErrorBoundaryClass {...props} />;
};

export default ErrorBoundary;